<template>
  <nly-content-wrapper>
    <nly-content-header>
      <nly-row class="col-12">
        <nly-row class="col-12">
          <nly-col xs="12" sm="12" md="12" lg="9" xl="9" class="form-inline" style="justify-content: left;">
            <!-- <i :class="this.$route.meta.icon + ' text-info'" class="icon" ></nly-icon>
            <span>{{this.$route.name}}</span>-->
          </nly-col>
          <nly-col xs="12" sm="12" md="12" lg="3" xl="3" class="form-inline align-self-start" style="justify-content: right;">
            <nly-button-group>
              <nly-button variant="info" @click="PageList" button-class="mr-2">查询</nly-button>
              <nly-button variant="info" button-class="mr-2" @click="reset">重置</nly-button>
              <nly-button @click="showFunction" variant="info" button-class="mr-2">
                <i :class="show ? 'fas fa-angle-down mr-1' : 'fas fa-angle-up mr-1'" />
                {{ show ? "折叠" : "展开" }}
              </nly-button>
            </nly-button-group>
          </nly-col>
        </nly-row>
        
        <nly-row class="ml-1 mb-2 lr mt-4" v-show="show">
          <nly-col xs="12" sm="12" md="12" lg="12" xl="12" class="form-inline" style="justify-content: left;">
            <form-input
              title="流程名称"
              id="processName"
              labelStyle
              rightStyle="width:120px;"
              class="ml-2"
              v-show="show"
              v-model="postData.processName"
            ></form-input>
            <form-select
              title="状态"
              class="ml-2"
              rightStyle="width:120px;"
              v-show="false"
              v-model="postData.status"
              :dataList="[
                { key: 0, title: '正常' },
                { key: 2, title: '停用' }
              ]"
            ></form-select>
          </nly-col>
        </nly-row>
      </nly-row>
      <nly-container fluid></nly-container>
    </nly-content-header>
    <div class="tabpanel_tab_spacer"></div>
    <div>
      <a-button type="primary" class="crm-btn" @click="EdiItem">编辑</a-button>
      <a-button type="primary" class="crm-btn" @click="Disable">删除</a-button>
      <a-button type="primary" class="crm-btn" @click="AddItem">新增</a-button>
    </div>
    <nly-content>
      <!-- 列表 -->
      <a-table
        :columns="columns"
        :components="components"
        :data-source="data"
        :scroll="{ x: 500, y: 500}"
        bordered
        :pagination="pagination"
        @change="onTableChange"
        :row-selection="{selectedRowKeys: selectedKeys, onChange: selection}"
      ></a-table>
      <!-- modal 弹窗  -->
      <a-modal
        v-model="eidtModelShow"
        centered
        on-ok="handleok"
        :title="editItem.id ? '编辑' : '新增'"
        width="65%"
      >
        <div id="components-form-demo-advanced-search">
          <a-form
            class="ant-advanced-search-form"
            :form="form"
            :label-col="{ span: 10 }"
            :wrapper-col="{ span: 20 }"
            @submit="handleSubmit"
          >
            <!-- <div class="line" style="color:#1980Ff;font-size:15px;">基本信息</div> -->
            <a-row :gutter="24">
              <a-col :span="10">
                <a-form-item label="流程名称">
                  <a-input
                    v-decorator="['processName', { rules: [{ required: true, message: '流程名称不能为空' }] }]"
                    placeholder="请输入流程名称"
                    :disabled="isDisabled"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="10" :push="2" :style="isShow">
                <a-form-item label="流程分类">
                  <a-select
                    v-decorator="['processType', { rules: [{ required: true, message: '请选择流程分类' }] }]"
                    placeholder="请选择流程分类"
                  >
                    <a-select-option value="1">客户审批</a-select-option>
                    <a-select-option value="2">入职审批</a-select-option>
                    <a-select-option value="3">离职审批</a-select-option>
                    <a-select-option value="4">任务审批</a-select-option>
                    <a-select-option value="5">提现审批</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="10">
                <a-form-item label="流程排序">
                  <a-input
                    v-decorator="['processSort', { rules: [{ required: true, message: '流程排序不能为空' }] }]"
                    placeholder="请输入流程排序"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="10" :push="2">
                <a-form-item label="审批方式">
                  <a-select
                    v-decorator="['approvalMode', { rules: [{ required: true, message: '请选择审批方式' }] }]"
                    placeholder="请选择审批方式"
                  >
                    <a-select-option value="1">会签</a-select-option>
                    <a-select-option value="2">或签</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="10">
                <a-form-item label="审批人类型">
                  <a-select
                    v-decorator="['approvalType', { rules: [{ required: true, message: '请选择审批人类型' }] }]"
                    placeholder="请选择审批人类型"
                  >
                    <a-select-option value="1">个人</a-select-option>
                    <a-select-option value="2">职务</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="10" :push="2">
                <a-form-item label="审批人">
                  <a-input-search
                    v-decorator="['approvalUserName', { rules: [{ required: true, message: '审批人不能为空' }] }]"
                    placeholder="选择用户"
                    @change="() => (approvalUserVisible = true)"
                    @click="() => (approvalUserVisible = true)"
                    @search="() => (approvalUserVisible = true)"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="22" :pull="5">
                <a-form-item label="备注">
                  <a-textarea
                    placeholder="请输入备注"
                    :rows="5"
                    v-decorator="['remarks', { rules: [{ required: false, message: '' }] }]"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <template slot="footer">
          <a-button type="primary" html-type="submit" @click="handleSubmit">保存</a-button>
          <a-button :style="{ marginLeft: '8px' }" @click="handleReset">重置</a-button>
          <a-button :style="{ marginLeft: '8px' }" @click="() => (eidtModelShow = false)">关闭</a-button>
        </template>
      </a-modal>

      <a-modal v-model="approvalUserVisible" title="用户选择" centered on-ok="handleok" width="300px">
        <div style="height: 400px;overflow-y:scroll;">
          <a-input-search style="margin-bottom: 8px" placeholder="输入用户名称" @change="onChange" />
          <div v-show="treeAShow">
            <a-tree
              v-model="checkedUserKeys"
              :tree-data="userSearchData"
              :show-icon="true"
              :expanded-keys="expandedUserKeys"
              @expand="expanedChange"
              :defaultExpandAll="true"
              checkable
              @check="approvalUserCheck"
            >
              <a-icon slot="user" type="user" />
            </a-tree>
          </div>
          <div v-show="treeBShow">
            <a-tree
              v-model="checkedUserKeys"
              :tree-data="userAllData"
              :show-icon="true"
              checkable
              :defaultExpandAll="true"
              @check="approvalUserCheck"
            >
              <a-icon slot="user" type="user" />
            </a-tree>
          </div>
        </div>
        <template slot="footer">
          <a-button key="submit" type="primary" @click="() => (approvalUserVisible = false)">确定</a-button>
          <a-button key="back" @click="() => (approvalUserVisible = false)">关闭</a-button>
        </template>
      </a-modal>
    </nly-content>
  </nly-content-wrapper>
</template>

<script>
import { FormInput, FormSelect } from "@/components/Form";
import { save, pageList, disable, enable } from "@/api/approvalProcess";
import { listToMap } from "@/utils/tool/map";
import { components } from "@/utils/antTableComponents";
import { TreeDataOffice } from "@/api/office";
import { officeUserListToTree, searchInTreeData } from "@/utils/tree";
import Vue from "vue";
const basePostData = {
  "current": 1,
  "size": 20
};

export default {
  components: {
    FormInput,
    FormSelect
  },
  data() {
    const columns = [
      {
        title: "流程名称",
        dataIndex: "processName",
        key: "processName",
        width: 120
      },
      {
        title: "流程分类",
        dataIndex: "processType",
        key: "processType",
        width: 120,
        customRender: (val, row) => {
          const type = [
            "客户审批",
            "入职审批",
            "离职审批",
            "任务审批",
            "提现审批"
          ];
          return type[val - 1];
        }
      },
      {
        title: "流程排序",
        dataIndex: "processSort",
        key: "processSort",
        width: 120
      },
      {
        title: "审批人类型",
        dataIndex: "approvalType",
        key: "approvalType",
        width: 120,
        customRender: (val, row) => {
          return val == 1 ? "个人" : "职务";
        }
      },
      {
        title: "审批方式",
        dataIndex: "approvalMode",
        key: "approvalMode",
        width: 120,
        customRender: (val, row) => {
          return val == 1 ? "会签" : "或签";
        }
      },
      {
        title: "审批人",
        dataIndex: "approvalUserName",
        key: "approvalUserName",
        width: 120
      },
      {
        title: "备注",
        dataIndex: "remarks",
        key: "remarks",
        width: 120
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status",
        width: 120,
        customRender: (text, row) => {
          return "正常";
        }
      },
      {
        title: "操作",
        dataIndex: "id",
        key: "id",
        width: 120,
        customRender: (text, row) => {
          return (
            <div class="icons-list">
              <a
                href="javascript:;"
                title="添加下一步审批流程"
                class="mr-1"
                onClick={() => this.AddNextItem(row)}
              >
                添加下一步
              </a>
            </div>
          );
        }
      }
    ];

    //表格 头部 可伸缩
    this.components = components(columns);
    return {
      fileList: [],
      postData: { ...basePostData },
      data: [],
      count: 0,
      columns,
      validateStatus: "success",
      isShow: "display:block",
      form: this.$form.createForm(this, { name: "advanced_search" }),
      errorMsg: null,
      isDisabled: false,
      pagination: {
        defaultPageSize: 20,
        current: 1,
        pageSize: 20,
        total: 0,
        showTotal: total => {
          return (
            <div>
              共 {total} 条数据，每页
              <a-input-number
                value={this.pagination.pageSize}
                min={1}
                max={500}
                onPressEnter={e => this.changePageSize(e)}
              />
              条
            </div>
          );
        },
        showQuickJumper: true,
        showLessItems: true
      },
      show: false, //是否显示
      editItem: {}, //新增/编辑对象
      selectedKeys: [],
      approvalUserVisible: false, //共享用户弹窗
      checkedUserKeys: [], //共享用户keys
      userSearchData: [], //用户搜索数据
      userAllData: [], //用户所有tree数据
      treeAShow: false, //搜索用户tree
      treeBShow: true, //用户tree
      approvalUserNames: "",
      approvalUserIds: "",
      expandedUserKeys: [],
      eidtModelShow: false,
      selectedIds: [],
      selectedData: []
    };
  },
  mounted() {
    this.PageList();
    TreeDataOffice({ isLoadUser: 2 }).then(response => {
      const { data } = response;
      const childrenNav = [];
      officeUserListToTree(data, childrenNav, "0");
      this.userAllData = childrenNav;
      this.userSearchData = childrenNav;
    });
  },
  methods: {
    //添加
    AddItem() {
      this.editItem = {};
      this.fileList = [];
      this.detailData = [];
      this.eidtModelShow = true;
      this.checkedUserKeys = [];
      this.handleReset();
    },
    //添加一下步
    AddNextItem(data) {
      this.eidtModelShow = true;
      this.form = this.$form.createForm(this, {
        mapPropsToFields: () => {
          return {
            processName: this.$form.createFormField({
              value: data.processName
            }),
            processType: this.$form.createFormField({
              value: data.processType.toString()
            }),
            processSort: this.$form.createFormField({
              value: data.processSort + 1
            }),
            approvalType: this.$form.createFormField({
              value: data.approvalType.toString()
            }),
            approvalMode: this.$form.createFormField({
              value: data.approvalMode.toString()
            })
          };
        }
      });
    },
    //编辑
    EdiItem() {
      if (this.selectedData.length != 1) {
        this.$message.warn("请选择一条数据");
        return false;
      }
      this.eidtModelShow = true;
      const data = this.selectedData[0];
      this.editItem = { ...data };
      this.approvalUserIds = data.approvalUserId;
      //form赋值
      this.form = this.$form.createForm(this, {
        mapPropsToFields: () => {
          return {
            approvalUserName: this.$form.createFormField({
              value: data.approvalUserName
            }),
            processName: this.$form.createFormField({
              value: data.processName
            }),
            processType: this.$form.createFormField({
              value: data.processType.toString()
            }),
            processSort: this.$form.createFormField({
              value: data.processSort
            }),
            approvalType: this.$form.createFormField({
              value: data.approvalType.toString()
            }),
            approvalMode: this.$form.createFormField({
              value: data.approvalMode.toString()
            }),
            remarks: this.$form.createFormField({
              value: data.remarks
            })
          };
        }
      });
      //用户tree赋值
      const userId = data.approvalUserId.split(",");
      for (let i = 0; i < userId.length; i++) {
        userId[i] = userId[i] + "_user";
      }
      this.checkedUserKeys = userId;
    },
    // 获取列表
    PageList() {
      const { postData } = this;
      pageList(postData)
        .then(response => {
          if (response.code === 200) {
            const { data } = response;
            const { records, total, current, size } = data;
            this.data = records;
            Object.assign(this.pagination, {
              total
            });
          }
        })
        .catch(error => {});
    },
    // 停用审批流程
    Disable() {
      let _this = this;
      this.$confirm({
        title: '提示',
        content: '您确定要停用吗？',
        onOk() {
            disable(_this.selectedIds)
              .then(response => {
                if (response.code === 200) {
                  _this.$message.success('停用成功');
                  //刷新 列表
                  _this.PageList();
                  _this.checkedUserKeys = [];
                } 
              })
        },
        onCancel() {
        },
      });
    },
    //启用审批流程
    Enable(item) {
      enable({ id: item.id })
        .then(response => {
          if (response.code === 200) {
            this.$message.success("启用成功");
            //刷新 列表
            this.PageList();
          }
        });
        
    },
    handleAdd() {
      const { count, detailData } = this;
      const newData = {
        key: count,
        commodityName: "",
        price: "",
        discount: "",
        counts: "",
        specs: "",
        totalPrice: ""
      };
      this.detailData = [...detailData, newData];
      this.count = count + 1;
    },
    //获取
    showFunction() {
      this.show = !this.show;
    },
    //表单重置
    handleReset() {
      this.form.resetFields();
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        console.log("开始保存:", this.editItem);
        if (!err) {
          const r = /^\+?[1-9][0-9]*$/; // 正整数
          if (!r.test(values.processSort)) {
            this.$message.error("排序只能输入正整数");
            return;
          }
          const id = this.editItem.id;
          this.editItem = { ...values };
          this.editItem.id = id;
          this.editItem.approvalUserId = this.approvalUserIds;
          save(this.editItem)
            .then(response => {
              if (response.code === 200) {
                this.$message.success("保存成功");
              
                //刷新 列表
                this.PageList();
                this.eidtModelShow = false;
              } else {
                this.$message.error(response.message);
                // this.$nlyaToast.toast(response.message, {
                //   title: `错误`,
                //   variant: "danger",
                //   solid: true
                // });
              }
            })
            
        }
      });
    },
    selection(keys, info) {
      this.selectedKeys = keys;
      const ids = new Array();
      info.forEach(function(val) {
        ids.push(val.id);
      });
      this.selectedIds = ids;
      this.selectedData = info;
    },
    onTableChange(pagination, filters, sorter) {
      Object.assign(this.postData, {
        "current": pagination.current,
        "size": pagination.pageSize
      });
      Object.assign(this.pagination, {
        current: pagination.current,
        pageSize: pagination.pageSize
      });
      this.PageList();
    },
    changePageSize(e) {
      const value = e.target.value;
      const { pagination } = this;

      console.log(e, value);
      Object.assign(this.postData, {
        "size": value
      });
      Object.assign(this.pagination, {
        pageSize: Number.parseInt(value)
      });
      this.PageList();
    },
    reset() {
      this.postData = { ...basePostData };
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.detailData];
      const target = dataSource.filter(item => key === item.key)[0];
      if (target) {
        target[dataIndex] = value;
        this.detailData = dataSource;
      }
    },
    approvalUserCheck(keys, info) {
      console.log(keys);
      this.approvalUserNames = "";
      this.approvalUserIds = "";
      if (info.checkedNodes.length > 0) {
        for (let i = 0; i < info.checkedNodes.length; i++) {
          const id = info.checkedNodes[i].data.props.id;
          const name = info.checkedNodes[i].data.props.name;
          if (id.indexOf("user") != -1) {
            this.approvalUserNames += name + ",";
            this.approvalUserIds += id.split("_")[0] + ",";
          }
        }
        this.approvalUserNames = this.approvalUserNames.slice(
          0,
          this.approvalUserNames.length - 1
        );
        this.approvalUserIds = this.approvalUserIds.slice(
          0,
          this.approvalUserIds.length - 1
        );
      }
      //审批人赋值
      this.form.setFieldsValue({
        approvalUserName: this.approvalUserNames
      });
    },
    //用户tree展开
    expanedChange(key, info) {
      this.expandedUserKeys = key;
    },
    //用户搜索
    onChange(e) {
      const value = e.target.value;
      console.log(value);
      if (value) {
        this.treeAShow = true;
        this.treeBShow = false;
        const keys = [];
        const treeData = searchInTreeData(
          keys,
          this.userAllData,
          "title",
          value
        );
        this.userSearchData = treeData;
        this.expandedUserKeys = keys;
      } else {
        this.treeAShow = false;
        this.treeBShow = true;
        //this.areaTreeData = treeAreaData;
        this.expandedUserKeys = [];
      }
    }
  },
  watch: {}
};
</script>
<style scoped>
.form-inline label {
  justify-content: left !important;
}
.form-inline > .col {
  margin-bottom: 1.5rem !important;
}
.icons-list >>> .anticon {
  margin-right: 8px;
  font-size: 16px;
}
.ant-advanced-search-form {
  padding: 24px;
  background: #fbfbfb;
}

.ant-advanced-search-form .ant-form-item {
  display: flex;
}

.ant-advanced-search-form .ant-form-item-control-wrapper {
  flex: 1;
}

#components-form-demo-advanced-search .ant-form {
  max-width: none;
}
#components-form-demo-advanced-search .search-result-list {
  margin-top: 16px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: center;
  padding-top: 80px;
}

/* tile uploaded pictures */
.upload-list-inline >>> .ant-upload-list-item {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline >>> .ant-upload-animate-enter {
  animation-name: uploadAnimateInlineIn;
}
.upload-list-inline >>> .ant-upload-animate-leave {
  animation-name: uploadAnimateInlineOut;
}
.ant-popover-inner {
  z-index: 2999;
}
/* .crm-btn {
  margin-left: 10px;
  margin-bottom: 10px;
} */
</style>
